// src/layouts/BasicLayout.tsx

import React, { useEffect, useState } from "react";
import { Layout, Menu, Dropdown, Avatar, Button } from "antd";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  LogoutOutlined,
} from "@ant-design/icons";
import { useNavigate, Outlet, useLocation } from "react-router-dom";
import { useAppSelector, useAppDispatch } from "@store/hooks";
import {
  selectUserName,
  selectUserAvatar,
  logout,
} from "@store/modules/userSlice";
import { generateMenu } from "@utils/auth";
import { asyncRoutes } from "@router/routes";
import "./BasicLayout.less";

const { Header, Sider, Content } = Layout;

const BasicLayout: React.FC = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const username = useAppSelector(selectUserName);
  const avatar = useAppSelector(selectUserAvatar);
  const [collapsed, setCollapsed] = useState(false);
  const [menuItems, setMenuItems] = useState<any[]>([]);

  // 切换侧边栏折叠
  const toggleCollapse = () => {
    setCollapsed(!collapsed);
  };
  const roles = useAppSelector(selectUserRoles);
  useEffect(() => {
    if (roles.length > 0) {
      const filtered = filterAsyncRoutes(asyncRoutes, roles);
      const childrenRoutes = filtered[0].children || []; // 因为第一个就是 / 基础布局
      setMenuItems(generateMenu(childrenRoutes));
    }
  }, [roles]);

  // 处理菜单点击：跳转路由
  const onMenuClick = (e: any) => {
    navigate(e.key);
  };

  // 用户头像菜单
  const onLogout = () => {
    dispatch(logout());
    navigate("/login");
  };

  const userMenu = (
    <Menu>
      <Menu.Item key="logout" onClick={onLogout} icon={<LogoutOutlined />}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <Layout className="basic-layout">
      {/* 侧边栏 */}
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="logo">
          <img src={require("@assets/img/logo.svg")} alt="logo" />
          {!collapsed && <span>后台管理</span>}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={[location.pathname]}
          onClick={onMenuClick}
          items={menuItems}
        />
      </Sider>

      <Layout className="site-layout">
        {/* 头部 */}
        <Header className="site-layout-header" style={{ padding: 0 }}>
          <Button
            type="text"
            onClick={toggleCollapse}
            style={{ marginLeft: "16px" }}
          >
            {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
          </Button>
          <div className="header-right">
            <Dropdown overlay={userMenu}>
              <span className="header-avatar">
                <Avatar size="small" src={avatar} />
                <span style={{ marginLeft: 8 }}>{username}</span>
              </span>
            </Dropdown>
          </div>
        </Header>

        {/* 内容区 */}
        <Content className="site-layout-content">
          <Outlet /> {/* 渲染子路由对应的页面 */}
        </Content>
      </Layout>
    </Layout>
  );
};

export default BasicLayout;
